<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    @ok="handleSubmit"
    :width="800"
  >
    <div class="sub-title">单据信息</div>
    <BasicForm @register="registerForm">
      <template #user="{ model }">
        <SelectUser
          v-model:value="model.personIds"
          suffix="ant-design:setting-outlined"
          placeholder="请选择经手人员"
        />
      </template>
      <template #relation="{ model }">
        <a-input
          v-model:value="relationKeyName"
          placeholder="请选择关联单据"
          :disabled="isNil(model.type)"
          @click="handleRelationChange"
        >
          <template #suffix>
            <Icon icon="ant-design:ellipsis-outlined" />
          </template>
        </a-input>
      </template>
    </BasicForm>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="openModal(true, { type: 'checkbox' })"> 添加 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'count'">
          <a-input-number v-model:value="record.count" />
        </template>
        <template v-if="column.dataIndex == 'action'">
          <TableAction
            :actions="[
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <SelectModal @register="registerSelectModal" @success="handleSuccess" />
    <RelationModal
      :type="relationType"
      :id="relationKeyId"
      @register="registerRelationModal"
      @success="handleRelationSuccess"
    />
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { BasicTable, useTable, BasicColumn, TableAction, FormSchema } from '/@/components/Table';
  import SelectModal from '../../bom/components/SelectModal.vue';
  import RelationModal from './RelationModal.vue';
  import SelectUser from '/@/components/Form/src/components/SelectUser.vue';
  import {
    getStoreManagementInfo,
    addStoreManagement,
    updateStoreManagement,
  } from '/@/api/erp/store/management';
  import { Icon } from '/@/components/Icon';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { isNil } from 'lodash-es';

  const { t } = useI18n();
  const FormSchema: FormSchema[] = [
    {
      field: 'code',
      label: '单据编号',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入单据编号',
      },
    },
    {
      field: 'name',
      label: '单据名称',
      component: 'Input',
      required: true,
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入单据名称',
      },
    },
    {
      field: 'type',
      label: '单据类型',
      component: 'Select',
      required: true,
      colProps: { span: 24 },
      componentProps: ({ formModel }) => {
        return {
          placeholder: '请选择单据类型',
          allowClear: false,
          options: [
            { label: '入库单', value: 1 },
            { label: '出库单', value: 0 },
          ],
          onChange: () => {
            formModel.relationKeyId = '';
            relationKeyName.value = '';
            console.log('formModel', formModel);
          },
        };
      },
    },
    {
      field: 'relationKeyId',
      label: '关联单据',
      component: 'Input',
      slot: 'relation',
      required: true,
      colProps: { span: 24 },
    },
    {
      field: 'personIds',
      label: '经手人员',
      component: 'Input',
      slot: 'user',
      required: true,
      colProps: { span: 24 },
    },
    {
      field: 'remark',
      label: '备注',
      component: 'InputTextArea',
      colProps: { span: 24 },
      componentProps: {
        placeholder: '请输入备注',
      },
    },
  ];

  const columns: BasicColumn[] = [
    {
      title: '产品编号',
      dataIndex: 'code',
      width: 100,
    },
    {
      title: '产品名称',
      dataIndex: 'name',
      width: 100,
    },
    {
      title: '规格型号',
      dataIndex: 'model',
      width: 100,
    },
    {
      title: '产品单位',
      dataIndex: 'unitName',
      width: 100,
    },
    {
      title: '数量',
      dataIndex: 'count',
      width: 100,
    },
  ];

  const { notification } = useMessage();
  const isUpdate = ref(true);
  const rowId = ref('');
  const relationType = ref();
  const relationKeyId = ref();

  const relationKeyName = ref('');
  const emit = defineEmits(['success']);

  const [registerForm, { setFieldsValue, resetFields, validate, getFieldsValue }] = useForm({
    labelWidth: 100,
    schemas: FormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerTable, { setTableData, getDataSource }] = useTable({
    title: '产品列表',
    columns,
    striped: false,
    bordered: false,
    pagination: false,
    actionColumn: {
      width: 50,
      title: t('操作'),
      dataIndex: 'action',
      slots: { customRender: 'action' },
    },
  });

  const [registerSelectModal, { openModal }] = useModal();
  const [registerRelationModal, { openModal: openRelationModal }] = useModal();

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false, destroyOnClose: true });

    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      rowId.value = data.id;
      const record = await getStoreManagementInfo(data.id);
      relationType.value = record.type;
      relationKeyId.value = record.relationKeyId;
      setFieldsValue({
        ...record,
      });
      setTableData(record.caseErpStoreReceiptDetailList || []);
    } else {
      relationType.value = null;
      relationKeyId.value = '';
      relationKeyName.value = '';
    }
  });

  const getTitle = computed(() => (!unref(isUpdate) ? '新增单据' : '编辑单据'));

  const handleRelationChange = () => {
    openRelationModal(true, {
      type: getFieldsValue().type,
    });
  };

  const handleSuccess = async (data) => {
    data.map((x) => (x.id = ''));
    setTableData([...getDataSource(), ...data]);
  };
  const handleRelationSuccess = async (data) => {
    relationKeyName.value = data.theme;
    setFieldsValue({ relationKeyId: data.id });
  };

  const handleDelete = (record) => {
    const datasource = getDataSource().filter((x) => x.id !== record.id);
    setTableData(datasource);
  };

  const handleSubmit = async () => {
    try {
      const values = await validate();
      values.addCaseErpStoreReceiptDetailDtoList = getDataSource() || [];
      setModalProps({ confirmLoading: true });

      if (!unref(isUpdate)) {
        await addStoreManagement(values);
        notification.success({
          message: '新增单据',
          description: t('成功'),
        });
      } else {
        values.id = rowId.value;
        await updateStoreManagement(values);
        notification.success({
          message: '编辑单据',
          description: t('成功'),
        });
      }

      closeModal();
      emit('success');
    } catch (error) {
      setModalProps({ confirmLoading: false });
    }
  };
</script>
<style lang="less" scoped>
  .sub-title {
    padding-left: 7px;
    border-left: 8px solid #5e95ff;
    font-size: 16px;
    margin-bottom: 10px;
  }
</style>
